package com.example.myapplication;

import android.util.Log;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class TCPUtils implements Runnable{
    private static String ServerIP;
    private static int ServerPort;
    private static final String TAG = "TCP Thread";

    public Socket listen_socket = null;
    public InputStream inputStream = null;
    private PrintWriter pw = null;
    private DataInputStream dis;
    byte[] buff = new byte[4096];
    private String rcvMsg;
    private int rcvLen;

    public TCPUtils(String ip , int port){
        ServerIP = ip;
        ServerPort = port;
    }

    public void send(String msg){
        pw.println(msg);
        pw.flush();
    }

    @Override
    public void run() {
        try {
            listen_socket = new Socket(ServerIP,ServerPort);
//            listen_socket.setSoTimeout(5000);
            pw = new PrintWriter(listen_socket.getOutputStream(),true);
            inputStream = listen_socket.getInputStream();
            dis = new DataInputStream(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true){
            try {
                rcvLen = dis.read(buff);
                rcvMsg = new String(buff,0,rcvLen,"utf-8");
                Log.i(TAG, "TCP接收消息-->"+ rcvMsg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


//
//public class TCPUtils extends Thread {
//    private static final String IP = "192.168.124.8";
//    private static final int PORT = 8087;
//    private static final String TAG = "TCP Thread";
//
//    public Socket listen_socket = null;
//    public OutputStream outputStream = null;
//    public InputStream inputStream = null;
//    private PrintWriter pw = null;
//
//    public void run(){
//        // 建立监听套接字listen_socket;获取输入输出流
//        try {
//            listen_socket = new Socket(IP, PORT);
//            inputStream = listen_socket.getInputStream();
//            outputStream = listen_socket.getOutputStream();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        int len = 0;
//        byte[] buf = new byte[1024];
//        // 循环接收数据
//        while (listen_socket.isConnected()) {
//            try {
//                len = inputStream.read(buf);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            String RecvData = new String(buf, 0, len, Charset.forName("ASCII"));
//            Log.i(TAG, RecvData);
//        }
//    }
//
//    public void send(String msg){
//        pw.println(msg);
//        pw.flush();
//    }
//}
